// axios 封装
import axios from 'axios';
import Vue from 'vue';
import {
    Message,
} from 'element-ui';
// axios.defaults.baseURL = process.env.VUE_APP_BASE_API
axios.defaults.timeout = 1000 * 60; // 设置接口超时时间
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.interceptors.request.use(
    (config) => {
        const token = window.sessionStorage.getItem('token');
        if (token) {
            config.headers.common.Authorization = token;
        }
        return config;
    },
    (error) => Promise.reject(error),
);

axios.interceptors.response.use(
    (response) => response,
    (error) => {
    // 断网处理或者请求超时
        if (!error.response) {
            // 请求超时
            if (error.message.includes('timeout')) {
                Message.error('请求超时了,请稍后重试');
            } else {
                // 断网，可以展示断网组件
                Message.error('请检查网络连接是否正常');
            }
            return;
        }
        const { status } = error.response;
        switch (status) {
        case 500:
            Message.error('服务器内部错误');
            break;
        case 404:
            Message.error('未找到远程服务器');
            break;
        case 400:
            Message.error('数据异常');
            break;
        default:
            Message.error(error.response.data.message);
        }
        const resInfo = Promise.reject(error);
        return resInfo;
    },
);

Vue.prototype.$axios = axios;
export default axios;
// 封装动态url
let $host;
let $protocol;
let $port;
let $REQUEST_URL;
let $WSS_URL;
if (process.env.NODE_ENV === 'development') {
    // 开发环境
    /* $host = '172.17.11.59';
    $protocol = 'https:';
    $port = 1111; */
    $host = 'local';
    $protocol = '/';
    $port = '/';
    $REQUEST_URL = '/local/';
    $WSS_URL = '';
} else if (process.env.NODE_ENV === 'production') {
    // 生产环境
    const { protocol, hostname, port } = window.location;
    $host = protocol; // https:
    $protocol = hostname; // 172.17.11.59
    $port = port;
    $REQUEST_URL = `${$host}//${$protocol}:${$port}/`;
    $WSS_URL = `wss//${$protocol}:${$port}/`;
}

export {
    $REQUEST_URL,
    $WSS_URL,
};
